package cn.iocoder.yudao.module.gpt.api;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.gpt.api.dto.GPTSessionResponseDTO;
import cn.iocoder.yudao.module.gpt.api.dto.GPTUserMessageDTO;
import cn.iocoder.yudao.module.gpt.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.gpt.service.chat.GPTChatService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.system.enums.ApiConstants.VERSION;

@RestController // 提供 RESTful API 接口，给 Feign 调用
@DubboService(version = VERSION) // 提供 Dubbo RPC 接口，给 Dubbo Consumer 调用
@Validated
public class ChatApiImpl implements ChatApi{

    @Resource
    private GPTChatService gptChatService;
    @Override
    public CommonResult<String> ask(GPTUserMessageDTO gptUserMessageDTO) {
        gptChatService.getGPTAnswerWithFlux(gptUserMessageDTO);
        return success("OK");
    }

    @Override
    public CommonResult<GPTSessionResponseDTO> requestSessionId(Long userId,String sessionId) {
        String returnVal = gptChatService.validateSessionId(sessionId);
        if(StrUtil.isEmpty(returnVal) || !StrUtil.equals(returnVal,sessionId)){
            return CommonResult.error(ErrorCodeConstants.OPENAI_CHAT_REQUEST_FAILURE);
        }
        GPTSessionResponseDTO gptSessionResponseDTO = new GPTSessionResponseDTO();
        gptSessionResponseDTO.setSessionId(sessionId);
        gptSessionResponseDTO.setUserId(userId);
        return CommonResult.success(gptSessionResponseDTO);
    }
}
